package com.ruoyi.common.es;


import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.elasticsearch.client.elc.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.convert.MappingElasticsearchConverter;
import org.springframework.data.elasticsearch.core.mapping.SimpleElasticsearchMappingContext;

@Configuration
public class ElasticsearchClientConfig {

    private String host;

    private Integer port;

    public Integer getPort() {
        return port;
    }
    @Value("${elasticsearch.port:9300}")
    public void setPort(Integer port) {
        this.port = port;
    }

    @Value("${elasticsearch.host:143.64.24.67}")
    public void setHost(String host) {
        this.host = host;
    }

    //    public RestHighLevelClient
    @Bean(value = "elasticsearchClient")
    @Lazy
    public ElasticsearchClient init() {
        // 创建低级客户端
        RestClient restClient = RestClient.builder(
                new HttpHost(host,  port)).build();
        // 使用Jackson映射器创建传输层
        ElasticsearchTransport transport = new RestClientTransport(
                restClient, new JacksonJsonpMapper());
        // 创建API客户端
        ElasticsearchClient client = new ElasticsearchClient(transport);

        return client;
    }

//    @Bean(value = "elasticsearchClient")
//    @Lazy
//    public RestClient restClient() {
//        // 创建低级客户端
//        RestClient restClient = RestClient.builder(
//                new HttpHost(host,  port)).build();
//        // 使用Jackson映射器创建传输层
//
//        return restClient;
//    }

    @Lazy
    @Bean("elasticsearchTemplate")
    public ElasticsearchTemplate getElasticsearchTemplate(ElasticsearchClient elasticsearchClient){

        MappingElasticsearchConverter mappingElasticsearchConverter = new MappingElasticsearchConverter(new SimpleElasticsearchMappingContext());

        mappingElasticsearchConverter.afterPropertiesSet();

        ElasticsearchTemplate elasticsearchTemplate = new ElasticsearchTemplate(elasticsearchClient,mappingElasticsearchConverter);

        return elasticsearchTemplate;
    }
    public String getHost() {
        return host;
    }
}

